package com.hrm.document.handler;

import com.hrm.commons.beans.Document;
import com.hrm.commons.beans.User;
import com.hrm.document.service.IDocumentService;
import com.hrm.utils.PageModel;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;
import java.util.logging.Logger;

@Controller
@RequestMapping("/document")
public class DocumentHandler {


    @Autowired
    IDocumentService documentService;


    @RequestMapping("/findDocument")
    public String findDocument(@RequestParam(defaultValue = "1") int pageIndex, String title, Model model){
        PageModel pageModel = new PageModel();
        pageModel.setPageIndex(pageIndex);
        List<Document> documents = documentService.findDocument(title,pageModel);
        /*查询记录数*/
        int recordCount = documentService.findDocumentCount(title);
        pageModel.setRocordCount(recordCount);
        /*int i = 1/0;*/
        /*for (Document d:documents){
            System.out.println(d);
        }*/

        model.addAttribute("documents",documents);
        model.addAttribute("pageModel",pageModel);
        model.addAttribute("title",title);//数据回显使用
        return "/jsp/document/document.jsp";
    }


    //文件上传
    @RequestMapping("/addDocument")
    public String addDocument(Document document, HttpSession session,Model model) throws IOException {
       //System.out.println("上传的文档为："+document);

        //1.保存上传的文件到服务器
        String path = "E:/upload";
        //获取路径对应的文件
        File file =new File(path);
        if (!file.exists()){//上传的路径是否存在,如果不存在
            file.mkdirs(); //创建对应的路径
        }

        //获取原始文件名称:重名文件不会被覆盖掉（或者使用uuid）
        String filename = System.currentTimeMillis()+"-" + document.getFile().getOriginalFilename();
        //定义保存的文件，就是把MultipartFile转换为File,保存到服务器对应地址
        document.getFile().transferTo(new File(path,filename));
        //2.数据库中插入对应数据,设置给document的filename赋值
        document.setFilename(filename);
        //获取当前登录用户，也就是文档上传者
        User login_user = (User) session.getAttribute("login_user");
        document.setUser(login_user);
        //调用Service方法插入对应文档信息
        int rows = documentService.addDocument(document);
        if (rows>0){
            PageModel pageModel = new PageModel();
            int recordCount = documentService.findDocumentCount(null);
            pageModel.setRocordCount(recordCount);
            pageModel.getTotalSize();
            return "redirect:/document/findDocument?pageIndex="+pageModel.getTotalSize();
        }else {
            model.addAttribute("fail","文档上传失败");
            return "/jsp/fail.jsp";
        }
    }


    /*文件修改*/
    @RequestMapping("/modifyDocument")
    public String modifyDocument(String flag,int pageIndex,Document document,Model model) throws IOException {
        if (flag == null){

            //按照Id查询原始文档信息
            document = documentService.findDocumentById(document.getId());
            model.addAttribute("document",document);
            model.addAttribute("pageIndex",pageIndex);
            return "/jsp/document/showUpdateDocument.jsp";
        }else {
            System.out.println("修改文档："+document);
            //判断修改文件信息时有没有上传新文件,如果有上传执行if中的代码，如果没有上传新的文件则不执行
            if (!document.getFile().isEmpty()){

                String path = "E:/upload";
                //获取原始目标文档信息
                Document target = documentService.findDocumentById(document.getId());
                //判断原始文件是否存在
                File targetFile = new File(path,target.getFilename());
                if (targetFile.exists()){
                    //删除该数据库描述信息对应的原始文件
                    targetFile.delete();
                }
                //把修改后的接收到的新文件保存在服务器

                String filename = System.currentTimeMillis()+"-"+document.getFile().getOriginalFilename();
                document.getFile().transferTo(new File(path,filename));
                //新的文件名称保存到Document
                document.setFilename(filename);
            }
            //修改数据库

             int rows =  documentService.modifyDocument(document);
             if (rows > 0){

                 return "redirect:/document/findDocument?pageIndex="+pageIndex;
             }else {
                 model.addAttribute("fail","文档信息修改失败！");
                 return "/jsp/fail.jsp";
             }
        }
    }


    /*下载文档*/
    @RequestMapping("/downLoad")
    public ResponseEntity<Object> downLoad(int id,HttpServletRequest request) throws IOException {
        String path = "E:/upload";
        Document targetDocument = documentService.findDocumentById(id);
        String filename = targetDocument.getFilename();

        //获取下载的目标文件
        File file = new File(path,filename);

        //如果下载的文件存在
         if (file.exists()){

             //这种设置方式不包括IE浏览器
             //filename = new String(filename.getBytes("UTF-8"),"iso8859-1");
             filename = filenameEncoding(filename,request);
             //设置响应头的相应内容类型
             HttpHeaders headers = new HttpHeaders();
             headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
             headers.setContentDispositionFormData("attachment",filename);
             return new ResponseEntity<Object>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
         }
         else {
             String error = "下载的文档不存在!";
             //设置响应头的内容为HTML
             HttpHeaders headers = new HttpHeaders();
             MediaType mediaType = new MediaType("text","html", Charset.forName("UTF-8"));
             headers.setContentType(mediaType);
             return new ResponseEntity<Object>(error,headers,HttpStatus.OK);
         }
    }

   //解决IE等浏览器显示中文乱码问题
    //第一种方案
    /*public static String encodeFileName(HttpServletRequest request, String fileName) {

        String returnFileName = "";
        String agent = request.getHeader("User-Agent");
        boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
        try {

            if (isMSIE) {
                returnFileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                returnFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }

            if (returnFileName.length() > 150) {
                returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
                returnFileName = StringUtils.replace(returnFileName, " ", "%20");
            }

        } catch (Exception e) {
            Logger logger = null;
            logger.info("encodeFileName error...");
        }

        return returnFileName;
    }*/
   //第二种方案
    public static String filenameEncoding(String filename, HttpServletRequest request) throws UnsupportedEncodingException {
        // 获得请求头中的User-Agent
        String agent = request.getHeader("User-Agent");
        // 根据不同的客户端进行不同的编码

        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }  else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }


    /*文档删除*/
    @RequestMapping("/removeDocument")
    public String removeDocument(Integer[] ids,Model model){
        String path = "E:/upload";
        int rows = 0;
        //查找要删除的目标文档
        for (Integer id:ids){
            Document target = documentService.findDocumentById(id);
            File targetFile = new File(path,target.getFilename());
            //如果目标文档存在，从服务器删除文档
            if (targetFile.exists()){
                targetFile.delete();
            }
            //删除文档对应的数据库信息
            int i = documentService.removeDocument(id);
            if (i>0){
                rows++;
            }
        }


       if (rows == ids.length){
           return "redirect:/document/findDocument";
       }else {
           model.addAttribute("fail","文档删除失败");
           return "/jsp/fail.jsp";
       }
    }



}
